import { AppstoreOutlined, ClockCircleOutlined, CustomerServiceOutlined } from "@ant-design/icons";
import { Avatar, Badge, Button, Empty, Flex, Layout, message, Modal, Tabs } from "antd";
import { useContext, useEffect } from "react";
import Draggable from "react-draggable";
import styles from "./style.module.scss";
import useDraggable from "../../../hooks/useDraggable";
import useModal from "../../../hooks/useModal";
import { MyContext } from "../../../store";
import CustomerServiceFloatButton from "./CustomerServiceFloatButton";
import { setSipVisibleOperation } from "../../../store/sip/action";
import CallOutPopver from "./components/CallOutPopver";
import OutSessionList from "./components/OutSessionList";

const { Sider } = Layout;

export default () => {
  const {
    isModalOpen,
    showModal,
    hideModal,
    inCall,
    setCallType,
    callType,
    setInCall,
    callInfo,
    setCallInfo,
    mute,
    setMute,
    hold,
    setHold
  } = useModal();
  // 拖拽控制
  const { draggleRef, disabled, setDisabled, bounds, onStart } = useDraggable();

  const { sipContext, sipDispatch } = useContext(MyContext);

  useEffect(() => {
    const { sipMessage } = sipContext;
    if (sipMessage) {
      if (["OUTGOING_CALL", "INCOMING_CALL"].includes(sipMessage.event)) {
        // showModal()
        setCallInfo({
          phone: sipMessage.data.otherLegNumber
        });
        setCallType(sipMessage.event);
      }

      // 静音
      if ("MUTE" === sipMessage.event) {
        setMute(true);
      }

      //取消静音
      if ("UNMUTE" === sipMessage.event) {
        setMute(false);
      }

      // 保持
      if ("HOLD" === sipMessage.event) {
        setHold(true);
      }

      if (sipMessage.event === "CALL_END") {
        message
          .success(
            `呼叫结束:cause:${sipMessage.data.cause};code:${sipMessage.data.code};originator:${sipMessage.data.originator}`
          )
          .then((r) => r);
        hideModal();
      }

      if (sipMessage.event === "IN_CALL") {
        setHold(false);
        setInCall(true);
      }
    }
  }, [sipContext.sipMessage]);

  useEffect(() => {
    console.log(sipContext.visibleOperation, "sipContext.visibleOperation");
    if (sipContext.visibleOperation) {
      showModal();
    }
  }, [sipContext.visibleOperation]);

  return (
    <>
      <CustomerServiceFloatButton onClick={showModal} />
      <Modal
        wrapClassName={styles.zrjCSS}
        title={
          <div
            className={"flex h-32 w-full cursor-move items-center bg-gray-200"}
            onMouseOver={() => {
              if (disabled) {
                setDisabled(false);
              }
            }}
            onMouseOut={() => {
              setDisabled(true);
            }}
          ></div>
        }
        className={styles.modal}
        open={isModalOpen}
        onOk={hideModal}
        onCancel={() => {
          hideModal();
          sipDispatch(setSipVisibleOperation(false));
        }}
        destroyOnClose={true}
        width={700}
        mask={false}
        keyboard={false}
        maskClosable={false}
        style={{ right: "-200px" }}
        footer={false}
        zIndex={99998}
        modalRender={(modal) => (
          <Draggable
            disabled={disabled}
            bounds={bounds}
            nodeRef={draggleRef}
            onStart={(event, uiData) => onStart(event, uiData)}
          >
            <div ref={draggleRef}>{modal}</div>
          </Draggable>
        )}
      >
        <Layout style={{ minHeight: 0 }}>
          <Sider width="50" className={"bg-gray-100"} theme={"light"}>
            <Flex vertical={true} gap={15} align={"center"}>
              <Flex
                vertical={true}
                className={"mt-10"}
                gap={5}
                justify={"center"}
              >
                <Badge dot>
                  <Avatar
                    shape="square"
                    size={35}
                    icon={<CustomerServiceOutlined />}
                    className={"bg-white text-blue-500"}
                  />
                </Badge>
                <p className={"text-xs"}>忙碌中</p>
              </Flex>

              <CallOutPopver>
                <Button
                  type={"text"}
                  shape={"circle"}
                  icon={
                    <svg className="iconfont hover:text-blue-600" style={{ fontSize: "20px" }}>
                      <use xlinkHref="#icon-boda"></use>
                    </svg>
                  }
                ></Button>
              </CallOutPopver>
              <Button
                type={"text"}
                shape={"circle"}
                icon={
                  <AppstoreOutlined
                    style={{ fontSize: "20px" }}
                    className={"hover:text-blue-600"}
                  />
                }
              ></Button>
              <Button
                type={"text"}
                shape={"circle"}
                icon={
                  <ClockCircleOutlined
                    style={{ fontSize: "20px" }}
                    className={"hover:text-blue-600"}
                  />
                }
              ></Button>
            </Flex>
          </Sider>
          <Layout className={"min-h-0 bg-white"}>
            <Flex>
              <div
                style={{ flex: "230px" }}
                className={"border-r border-solid border-gray-200"}
              >
                <Tabs
                  defaultActiveKey="1"
                  centered
                  items={[
                    {
                      key: "1",
                      label: "外部会话",
                      children: (
                        <div className={"h-430 overflow-y-auto"}>
                          <OutSessionList />
                        </div>
                      )
                    },
                    {
                      key: "2",
                      label: "内部会话",
                      children: ""
                    }
                  ]}
                />
              </div>
              <div style={{ flex: "calc(100% - 230px)", height: "500px" }}>
                {callType ? (
                  <>
                    <div
                      className={
                        "flex h-40 items-center border-b border-solid border-gray-200 px-10 text-xs"
                      }
                    >
                      {inCall
                        ? "通话中"
                        : callType === "INCOMING_CALL"
                          ? "来电提醒"
                          : "呼叫中"}
                      {callType !== "INCOMING_CALL" && (
                        <>({sipContext?.sipCallTime})</>
                      )}
                    </div>

                    <div className={"py-20"}>
                      <div className={"h-400"}>
                        <Flex
                          vertical={true}
                          gap={15}
                          className={"text-center"}
                        >
                          <div className={"text-4xl"}>{callInfo.phone}</div>
                          <div className={"text-sm text-gray-400"}>
                            安徽合肥电信
                          </div>
                          {callType === "OUTGOING_CALL" && (
                            <div className={"text-sm"}>
                              主叫号码：{sipContext?.sipClient?.localAgent}
                            </div>
                          )}
                        </Flex>
                      </div>

                      <div>
                        {inCall ? (
                          <Flex gap={10} wrap={true} justify={"center"}>
                            <Button
                              className={"w-90"}
                              type={"primary"}
                              icon={
                                <svg className="iconfont">
                                  <use xlinkHref="#icon-guaduan"></use>
                                </svg>
                              }
                              danger
                              onClick={() => {
                                sipContext?.sipClient?.hangup?.();
                              }}
                              shape={"round"}
                            >
                              挂断
                            </Button>
                            {mute ? (
                              <Button
                                color="primary"
                                className={"w-90"}
                                variant="outlined"
                                shape={"round"}
                                onClick={() =>
                                  sipContext?.sipClient?.unmute?.()
                                }
                              >
                                取消静音
                              </Button>
                            ) : (
                              <Button
                                color="primary"
                                disabled={hold}
                                style={{ color: hold ? "#ffffff" : "" }}
                                className={"w-90"}
                                variant="outlined"
                                shape={"round"}
                                onClick={() => sipContext?.sipClient?.mute?.()}
                              >
                                静音
                              </Button>
                            )}

                            {hold ? (
                              <Button
                                color="primary"
                                className={"w-90"}
                                variant="outlined"
                                shape={"round"}
                                onClick={() =>
                                  sipContext?.sipClient?.unhold?.()
                                }
                              >
                                通话取回
                              </Button>
                            ) : (
                              <Button
                                disabled={mute}
                                style={{ color: mute ? "#ffffff" : "" }}
                                color="primary"
                                className={"w-90"}
                                variant="outlined"
                                shape={"round"}
                                onClick={() => sipContext?.sipClient?.hold?.()}
                              >
                                通话保持
                              </Button>
                            )}
                            {/*  <Button type="primary" className={'w-90'} shape={'round'}
                                    onClick={() => sipContext?.sipClient?.transfer?.('1111')}>
                              转接
                            </Button>
                            <Button type="primary" className={'w-90'} shape={'round'}>
                              咨询
                            </Button>
                            <Button type="primary" className={'w-90'} shape={'round'}>
                              自助服务
                            </Button>
                            <Button type="primary" className={'w-90'} shape={'round'}>
                              输入号码
                            </Button>*/}
                          </Flex>
                        ) : (
                          <Flex justify={"center"} gap={15}>
                            {callType === "INCOMING_CALL" && (
                              <Button
                                type="primary"
                                className={"w-90"}
                                shape={"round"}
                                onClick={() =>
                                  sipContext?.sipClient?.answer?.()
                                }
                              >
                                接通
                              </Button>
                            )}
                            <Button
                              className={"w-150"}
                              type={"primary"}
                              icon={
                                <svg className="iconfont">
                                  <use xlinkHref="#icon-guaduan"></use>
                                </svg>
                              }
                              danger
                              onClick={() => {
                                sipContext?.sipClient?.hangup?.();
                              }}
                              shape={"round"}
                            >
                              挂断
                            </Button>
                          </Flex>
                        )}
                      </div>
                    </div>
                  </>
                ) : (
                  <Empty description={"暂无消息"} className={"mt-200"} />
                )}
              </div>
            </Flex>
          </Layout>
        </Layout>
      </Modal>
    </>
  );
};
